package com.battery.eason.interceptor;

import com.battery.eason.config.JwtTokenUtil;
import com.battery.eason.pojo.RespBean;
import com.battery.eason.pojo.SysUser;
import com.battery.eason.service.ISysUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器
 *
 * @author HuangSiYuan
 * @since 2021-08-16
 */
@Configuration
public class UserInterceptor implements HandlerInterceptor {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    /*
    * 前置拦截
    * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截器内统一的错误返回都是未登录
        /*首先获取token请求头*/
        String authToken = request.getHeader(tokenHeader);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("autoToken:" + authToken);
        /*给请求头判空,判断是否存在,如果存在的话就说明有token令牌*/
        /*startsWith()方法一般用于检测某请求字符串是否以指定的前缀开始的。*/
        /*请求头的存在形式为: tokenHead + 空格 + token令牌 */
        response.setContentType("application/json;charset=utf-8");
        HttpSession session = request.getSession();
        if (null != authToken && !authToken.equals("") ) {
            /*通过token获取用户名*/
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            System.out.println("当前登录的用户名为: " + username);
            SysUser sysUser = sysUserService.getSysUserByUsername(username);
            // token存在用户名但未登录,因为当我们登录或注册成功之后会在session里面添加上所有的用户信息
            if (null != username && null == session.getAttribute(username)) {
                //说明用户名为空而且session里面没有信息
                //进行登录
                //更新到session里面去
                session.setAttribute(username,sysUser);
            }
            return true;
        }
        //响应前端
        response.getWriter().write(mapper.writeValueAsString(RespBean.error("您未登录, 请登陆后操作!")));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
